package filter.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 保存用户上一次访问时间
 */
public class CookieServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //确保输出编码不乱码
        req.setCharacterEncoding("gbk");
        resp.setCharacterEncoding("gbk");

        //创建写入对象
        PrintWriter out = resp.getWriter();
        //cookie,服务器端从客户端获取。
        Cookie[] cookies = req.getCookies();
        //判断cookie是否为空
        if(cookies!=null)
        {
            out.write("你上一次访问的时间：");
            for (int i = 0; i < cookies.length; i++) {
                //将每个cookie取出
                Cookie cookie = cookies[i];
                //判断cookie内容是否一致
                if (cookie.getName().equals("time")) {
                    //把字符串变成时间戳，然后用date转成时间
                    Date date=new Date(Long.parseLong(cookie.getValue()));
                    //以本地时间输出
                    out.write(date.toLocaleString());
                }
            }
        }else
        {
            out.write("这是你第一次访问本站。");
        }

        //服务器给客户端响应cookie
        Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");
        //设置cookie有效期保存一天，setMaxAge(小时*分钟*秒钟)
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req, resp);
    }
}
